<script setup lang='ts'>
import type { VxeGridInstance, VxeGridProps, VxePagerEvents } from 'vxe-table'

import { flowHttp } from '@fl/api/work-flow'
import { useRouter } from 'vue-router'

import { LEVEL_DICT, STATE_DICT, formCode } from './type'

const userId = window.sessionStorage.getItem('USER_ID') || ''
const router = useRouter()
const state = ref({
    CreatedName: '',
    CreatedTime: '',
    qiyfr: '',
    qiymc: '',
    xingm: '',
})
const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '企业名称',
        prop: 'qiymc',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '添加人',
        prop: 'CreatedName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '企业管理员',
        prop: 'xingm',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '企业法人',
        prop: 'qiyfr',
        valueType: 'copy',
    },
    // {
    //     colProps: {
    //         span: 8,
    //     },
    //     fieldProps: {
    //         endPlaceholder: '请选择结束时间',
    //         format: 'YYYY-MM-DD',
    //         startPlaceholder: '请选择开始时间',
    //         type: 'daterange',
    //     },
    //     label: '申请时间区间',
    //     prop: 'CreatedTime',
    //     valueType: 'date-picker',
    // },
]
type RowVO = {
    CreatedTime: string
    hezlx: string
    qiyfr: string
    qiyjb_Id: string
    qiyjc: string
    qiymc: string
    tongyxydm: string
    xingm: string
}
const xGrid = ref<VxeGridInstance<RowVO>>()
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'qiymc', title: '企业名称' },
        { field: 'qiyjc', title: '企业简称' },
        { slots: { default: 'qiyjb' }, title: '企业级别' },
        { field: 'tongyxydm', title: '信用代码' },
        { field: 'qiyfr', title: '企业法人' },
        { field: 'hezlx', title: '合作类型' },
        { field: 'xingm', title: '企业管理员' },
        { slots: { default: 'State' }, title: '申请状态' },
        { field: 'CreatedTime', title: '申请时间' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 550,
    keepSource: true,
    loading: false,
    showOverflow: true,
})
function search() {
    tablePage.currentPage = 1
    findList()
}
function reset() {
    state.value = {
        CreatedName: '',
        CreatedTime: '',
        qiyfr: '',
        qiymc: '',
        xingm: '',
    }
    findList()
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
    findList()
}
async function findList() {
    gridOptions.loading = true
    try {
        const { data } = await flowHttp('query', {
            body: {
                data: {
                    code: formCode,
                    filter: [
                        {
                            filed: 'qiymc',
                            value: state.value.qiymc,
                        },
                        {
                            filed: 'qiyfr',
                            value: state.value.qiyfr,
                        },
                        {
                            filed: 'xingm',
                            value: state.value.xingm,
                        },
                        {
                            filed: 'CreatedName',
                            value: state.value.CreatedName,
                        },
                    ],
                    pageInfo: {
                        page: tablePage.currentPage,
                        size: tablePage.pageSize,
                    },
                    requireCount: '1',
                },
            },
        })
        console.log(data)
        gridOptions.loading = false
        if (data.code === 200) {
            tablePage.total = data?.data?.PagingInfo?.DataCount ?? 0
            gridOptions.data = data?.data?.Datas ?? []
        }
        else {
            ElMessage.error(data.msg)
        }
    }
    catch (error) {
        gridOptions.loading = false
    }
}
findList()
function showInfo(row: any) {
    console.log('🚀 ~ row:', row)
    router.push(
        {
            path: '/business-management/application-settlement-detail',
            query: {
                dataId: row.ObjectID,
            },
        },
    )
}
async function rowSubmit(row: any) {
    try {
        const objectId = row.ObjectID
        deleteFields(row, '_X_ROW_KEY', 'ApplyTime', 'BizSheetVersion', 'CreatedBy', 'CreatedByParentId', 'CreatedName', 'CreatedParentName', 'CreatedTime', 'FlowItemId', 'FlowStatus', 'IDFullPath', 'ModifiedBy', 'ModifiedTime', 'Name', 'NameFullPath', 'OwnerId', 'OwnerParentId', 'RunningInstanceId', 'SequenceNo', 'SheetCode', 'State', 'TreeListParentID', 'WorkFlowVersion', 'WorkflowCode', 'ObjectID')
        console.log(row)
        const params = {
            body: {
                data: {
                    data: {
                        ...row,
                    },
                    formCode, // pc端
                    objectId,
                    participativeId: '',
                },

            },
            header_param: {
                userId,
            },
        }
        const { data } = await flowHttp('add', params)
        console.log('🚀 ~ rowSubmit ~ result:', data)
        if (data.code === 200)
            ElMessage.success('提交成功')

        else ElMessage.error(data.msg)
        findList()
    }
    catch (error) {

    }
}

function deleteFields(obj: any, ...fields: any) {
    for (const field of fields) {
        if (field in obj)
            delete obj[field]
    }
}
</script>

<template>
    <div class="mb-20 flex bg-white p-30">
        <div class="flex-1 pr-24">
            <PlusForm v-model="state"
                      :columns="columns"
                      :row-props="{ gutter: 20 }"
                      label-width=""
                      :has-footer="false"
            />
        </div>

        <div class="">
            <ElButton type="primary"
                      @click="search"
            >
                搜索
            </ElButton>

            <ElButton @click="reset">
                重置
            </ElButton>
        </div>
    </div>

    <div class="bg-white p-30">
        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
        >
            <template #qiyjb="{ row }">
                <span v-if="row.qiyjb_Id"
                      class="px-8 py-2"
                      :style="{
                          color: `${LEVEL_DICT[row.qiyjb_Id].color}`,
                          background: `${LEVEL_DICT[row.qiyjb_Id].bac}`,

                      }"
                >
                    {{ LEVEL_DICT[row.qiyjb_Id].label }}
                </span>
            </template>

            <template #State="{ row }">
                <span v-if="row.State"
                      class="px-8 py-2"
                      :style="{
                          color: `${STATE_DICT[row.State].color}`,
                          background: `${STATE_DICT[row.State].bac}`,

                      }"
                >
                    {{ STATE_DICT[row.State].label }}
                </span>
            </template>

            <template #operate="{ row }">
                <span class="mr-10 cursor-pointer text-#F53639"
                      @click="showInfo(row)"
                >查看</span>

                <span v-if="row.State === 2"
                      class="cursor-pointer text-#86909C"
                      @click="rowSubmit(row)"
                >
                    通过
                </span>
            </template>

            <template #pager>
                <vxe-pager v-model:current-page="tablePage.currentPage"
                           v-model:page-size="tablePage.pageSize"
                           background
                           :total="tablePage.total"
                           :layouts="['Home', 'PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
                           @page-change="handlePageChange"
                />
            </template>
        </vxe-grid>
    </div>
</template>
